#include "my.h"

const int width = 800;
const int height = 600;

// 窗口大小改变时的回调
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    glViewport(0, 0, width, height);
}

void processInput(GLFWwindow *window)
{
    // 按下 esc 关闭窗口
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}

int main()
{
    glfwInit();

    // 配置 GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif

    // 选择场景
    int i = -1;
    while (i < 0 || i >= nScenes) {
        printf("scene to play [0-%d]: ", nScenes-1);
        if (scanf("%d", &i) != 1) {
            puts("invalid input");
            exit(2);
        }
    }
    Scene *scene = scenes[i];

    // 创建窗口
    GLFWwindow* window = glfwCreateWindow(width, height, "LearnOpenGL", NULL, NULL);
    if (!window) {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // 初始化 GLAD
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    // 初始化 viewport
    glViewport(0, 0, width, height);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);


    // 既然是图形程序, 就要有消息循环
    scene->init();
    while (!glfwWindowShouldClose(window)) {
        processInput(window); // 处理输入
        scene->render(); // 渲染
        glfwSwapBuffers(window); // 双缓冲
        glfwPollEvents(); // 派发事件
    }
    scene->destroy();

    glfwTerminate();

    return 0;
}
